<script setup lang="ts">
import login from '../api/login'
import {FormInstance, FormRules, ElMessage} from 'element-plus'
//验证码模态框是否出现，默认不展示
const isShow = ref(false)
const ruleFormRef = ref<FormInstance>()
import {ref, reactive} from "vue";
import {useRouter} from 'vue-router'
import Header from "../components/Header.vue";
import {useStore} from 'vuex'
const store = useStore()

const router = useRouter()


const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (login.loginForm.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass')
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== login.loginForm.pass) {
    callback(new Error("两次输入的密码不一致!"))
  } else {
    callback()
  }
}

const validateAccount = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('手机号格式不正确'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  pass: [{validator: validatePass, trigger: 'blur'}],
  checkPass: [{validator: validatePass2, trigger: 'blur'}],
  account: [{validator: validateAccount, trigger: 'blur'}],
})

// 注册
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      login.registerUser().then(res => {
        ElMessage.success('注册成功')
        router.push('/')
        clearInterval(login.timer)
        login.code_msg = '获取验证码'
        // token存储到本地
        window.sessionStorage.removeItem("token")
        window.localStorage.removeItem("token")
        if (login.remember) {
          window.localStorage.token = res.data.access
        } else {
          window.sessionStorage.token = res.data.access
        }
        const payload = res.data.access.split(".")[1]
        const payload_user = JSON.parse(window.atob(payload))
        store.commit('login', payload_user)

        formEl.resetFields()
      }).catch(err => {
        ElMessage.error(err.response.data.non_field_errors[0])
      })
    } else {
      ElMessage.error('请正确填写账号密码等信息')
    }
  })
}

// 登陆
const loginForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  // isShow.value = true
  formEl.validate(valid => {
    if (valid) {
      login.loginUser().then(res => {
        ElMessage.success('登陆成功')
        router.push('/')
        window.sessionStorage.removeItem("token")
        window.localStorage.removeItem("token")
        if (login.remember) {
          window.localStorage.token = res.data.access
        } else {
          window.sessionStorage.token = res.data.access
        }
        const payload = res.data.access.split(".")[1]
        const payload_user = JSON.parse(window.atob(payload))
        store.commit('login', payload_user)
        formEl.resetFields()
      }).catch(err => {
        ElMessage.error('登陆失败, 可能您的账号已封禁')
      })
    } else {
      ElMessage.error('请正确填写账号密码信息')
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


// 发送验证码
const sendCode = () => {
  //验证手机号
  if (login.loginForm.account === '') {
    ElMessage.error('请输入手机号')
    return
  }
  if (!/^1[3-9]\d{9}$/.test(login.loginForm.account)) {
    ElMessage.error('手机号格式不正确')
    return
  }
  // 两次密码是否一致
  if (login.loginForm.pass !== login.loginForm.checkPass) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  login.checkPhone().catch(res => {
    ElMessage.error('该手机号已被注册')
    return
  })
  // 倒计时
  clearInterval(login.timer)
  login.timer = setInterval(() => {
    // 为60秒可以发送验证码
    if (login.code_time === 60) {
      login.sendCode().then(res => {
        ElMessage.success('验证码发送成功')
      }).catch((err) => {
        ElMessage.error('验证码发送失败')
        login.code_time = err.response.data.interval
      })
    }

    // 倒计时
    login.code_time--
    login.code_msg = `${login.code_time}s后重发`
    if (login.code_time <= 0) {
      clearInterval(login.timer)
      login.code_msg = '获取验证码'
    }
  }, 1000)
}


// 验证码验证
//引入'vue3-puzzle-vcode'插件
import Vcode from 'vue3-puzzle-vcode'
import Img from '../assets/imgs/img.png'
import img_2 from '../assets/imgs/img_2.png'
//获取路由器
let $router = useRouter()

// 登录按钮
const loginsForm = (formEl: FormInstance | undefined) => {
  //展现验证码模态框
  isShow.value = true
  login.formObj = formEl
}
// 用户通过了验证
const success = (msg) => {
  isShow.value = false
  if (login.is_register) {
    submitForm(login.formObj)
  } else {
    loginForm(login.formObj)
  }
}
//用户点击遮罩层，关闭模态框
const close = () => {
  isShow.value = false
}
//用户验证失败
const fail = () => {
  ElMessage.error('验证码错误')
}

// 取消忘记密码
const cancelForget = (formEl: FormInstance | undefined) => {
  login.loginFormVisible = false
  formEl.resetFields()
}

// 确认忘记密码
const confirmForget = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  // isShow.value = true
  formEl.validate(valid => {
    if (valid) {
      login.forgetPassword().then(res => {
        ElMessage.success('密码修改成功')
        login.loginFormVisible = false
        formEl.resetFields()
        router.push('/')
      }).catch(err => {
        ElMessage.error('修改密码失败')
      })
    } else {
      ElMessage.error('请正确填写账号密码信息')
    }
  })
}

</script>

<template>
  <div class="login">
    <img src="../assets/imgs/login.png" alt="logo">
    <Header class="header"></Header>
    <div class="box" v-if="login.is_register">
      <div>
        <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="login.loginForm"
            status-icon
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
        >
          <el-form-item label="手机号" prop="account">
            <el-input v-model="login.loginForm.account" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="密码" prop="pass">
            <el-input v-model="login.loginForm.pass" type="password" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="确定密码" prop="checkPass">
            <el-input
                v-model="login.loginForm.checkPass"
                type="password"
                autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input style="width: 150px;margin-right:28px" v-model.number="login.loginForm.code"/>
            <el-button style="background-color:#53868B;color:#fff;" @click="sendCode">{{ login.code_msg }}</el-button>
          </el-form-item>
          <Vcode :show="isShow" @success="success" @close="close" @fail="fail" :imgs="[Img,img_2]"
                 style="width: 100px;height: 40px;margin-right:28px"></Vcode>
          <el-form-item class="register_account">
            <el-button type="primary" @click="loginsForm(ruleFormRef)">
              注册账号
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          </el-form-item>
        </el-form>
        <div class="have_account" style="bottom:5px">已有账号
          <span @click="login.is_register=false">立即登陆</span>
        </div>
      </div>
      <div class="remember"> <input type="checkbox" class="no" v-model="login.remember"/> <span>记住我</span> </div>
    </div>

    <div class="box" style="height: 270px" v-else>
      <div>
        <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="login.loginForm"
            status-icon
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
        >
          <el-form-item label="手机号" prop="account">
            <el-input v-model="login.loginForm.account" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="密码" prop="pass">
            <el-input v-model="login.loginForm.pass" type="password" autocomplete="off"/>
          </el-form-item>
          <!--          <el-form-item label="验证码" prop="code">-->
          <!--            <el-input style="width: 150px;margin-right:28px" v-model.number="login.loginForm.code"/>-->
          <Vcode :show="isShow" @success="success" @close="close" @fail="fail" :imgs="[Img,img_2]"
                 style="width: 100px;height: 40px;margin-right:28px"></Vcode>
          <!--            <el-button style="background-color:#53868B;color:#fff;">{{ login.code_msg }}</el-button>-->
          <!--          </el-form-item>-->
          <el-form-item class="register_account">
            <el-button type="primary" @click="loginsForm(ruleFormRef)">
              登陆
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          </el-form-item>
        </el-form>
        <div class="have_account" style="bottom:5px">没有账号 <span @click="login.is_register=true">立即注册</span></div>
        <div class="no_account" style="bottom:25px">已有账号 <span @click="login.loginFormVisible=true">忘记密码</span></div>
      </div>
      <div class="remember" style="bottom:45px"> <input type="checkbox" class="no" v-model="login.remember"/> <span>记住我</span> </div>
    </div>

  </div>
  <!--  忘记密码-->
  <el-dialog v-model="login.loginFormVisible" title="修改密码" width="500">
    <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="login.loginForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
    >
      <el-form-item label="手机号" prop="account">
        <el-input v-model="login.loginForm.account" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="新密码" prop="pass">
        <el-input v-model="login.loginForm.pass" type="password" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="确定密码" prop="checkPass">
        <el-input
            v-model="login.loginForm.checkPass"
            type="password"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input style="width: 150px;margin-right:28px" v-model.number="login.loginForm.code"/>
        <el-button style="background-color:#53868B;color:#fff;" @click="sendCode">{{ login.code_msg }}</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelForget(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="confirmForget(ruleFormRef)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.header {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
}

.login {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

body {
  background: none;
}

img {
  width: 100%;
  min-height: 100%;
}

.box {
  position: absolute;
  width: 500px;
  height: 340px;
  left: 0;
  margin: auto;
  right: 0;
  bottom: 0;
  top: 100px;
  padding: 50px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}

.register_account {
  float: right;
}

.have_account {
  margin-top: 20px;
  font-size: 14px;
  color: #999;
  position: absolute;
  bottom: 35px;
  left: 50%;
  transform: translateX(-50%);

  span {
    color: black;
    cursor: pointer;
    font-size: 16px;
  }
}

.have_account span:hover {
  color: #53868B;
}

.no_account {
  margin-top: 40px;
  font-size: 14px;
  color: #999;
  position: absolute;
  bottom: 5px;
  left: 50%;
  transform: translateX(-50%);

  span {
    color: red;
    cursor: pointer;
    font-size: 16px;
  }
}

.no_account span:hover {
  color: #53868B;
}

.remember {
  margin-top: 40px;
  font-size: 14px;
  color: #999;
  position: absolute;
  bottom: 28px;
  left: 20%;
  span {
    margin-left: 145px;
    font-size: 16px;
    color: red;
  }
}
</style>